package fr.obsmip.sedoo.core.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.obsmip.sedoo.core.domain.ObservatoryPerson;

@Repository
public class ObservatoryPersonDAOJPAImpl implements ObservatoryPersonDAO{

	protected EntityManager em;
	public EntityManager getEntityManager() {
		return em;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public ArrayList<ObservatoryPerson> findByObservatoryId(String observatoryId) {
		Long id = new Long(observatoryId);
		List<ObservatoryPerson> aux = em.createQuery("select observatoryPerson from ObservatoryPerson observatoryPerson where observatoryPerson.observatory.id="+id + " order by observatoryPerson.personName").getResultList();
      ArrayList<ObservatoryPerson> result = new ArrayList<ObservatoryPerson>();
      result.addAll(aux);
		return result;
	}
	
	@Override
	@Transactional
	public void delete(Long id) {
		
		ObservatoryPerson aux = getEntityManager().find(ObservatoryPerson.class, id);
		if (aux != null)
		{
			getEntityManager().remove(aux);
		}
	}
	
	@Override
	@Transactional
	public ObservatoryPerson save(ObservatoryPerson person) 
	{
		if (person.getId() == null)
		{
			getEntityManager().persist(person);
			return person;
		}
		else
		{
			getEntityManager().merge(person);
			return person;
		}
	}

	


}